package server.config;

import server.HttpServlet;

import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 记录Context信息
 */
public class Context {
    /**
     * 项目对应的URL
     */
    private String path;

    /**
     * 项目的根目录
     */
    private String docBase;

    /**
     * Servlet配置映射表
     */
    private Map<String, HttpServlet> servletMap = new ConcurrentHashMap<>();

    /**
     * 添加Servlet
     *
     * @param url Servlet对应的URL
     * @param httpServlet 要添加的Servlet
     */
    public void addServlet(String url, HttpServlet httpServlet) {
        servletMap.put(url, httpServlet);
    }

    /**
     * 根据给定的URL，获取对应的Servlet
     *
     * @param url 给定的URL
     * @return 对应的Servlet
     */
    public HttpServlet resolveServlet(String url) {
        return servletMap.get(url);
    }

    /**
     * 根据给定的URL，获取对应的静态资源
     *
     * @param url 给定的URL
     * @param appBase 项目的根目录
     * @return 对应的静态资源
     */
    public InputStream resolveStatic(String url, String appBase) {
        String path = String.format("%s/%s/%s", appBase, docBase, url);
        return getClass().getClassLoader().getResourceAsStream(path);
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getDocBase() {
        return docBase;
    }

    public void setDocBase(String docBase) {
        this.docBase = docBase;
    }
}
